package com.by.session;

import com.by.config.Configuration;
import com.by.executor.SimpleExecutor;
import com.by.mapping.MappedStatement;

import java.lang.reflect.Proxy;
import java.util.List;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;
    private SimpleExecutor executor;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        this.executor = new SimpleExecutor(configuration);
    }

    @Override
    public <T> T getMapper(Class<T> mapperInterface) {
        return (T) Proxy.newProxyInstance(
                mapperInterface.getClassLoader(),
                new Class[]{mapperInterface},
                (proxy, method, args) -> {
                    String methodName = method.getName();
                    String statementId = mapperInterface.getName() + "." + methodName;

                    MappedStatement mappedStatement = configuration.getMappedStatement(statementId);
                    if (mappedStatement == null) {
                        throw new RuntimeException("Statement not found: " + statementId);
                    }

                    // 判断返回类型是否为 List
                    Class<?> returnType = method.getReturnType();
                    if (returnType == List.class) {
                        return executor.query(mappedStatement, args == null ? null : args[0]);
                    } else {
                        // 如果不是 List，则返回单个对象
                        List<T> results = executor.query(mappedStatement, args == null ? null : args[0]);
                        if (results.isEmpty()) {
                            return null; // 如果没有结果，返回 null
                        }
                        return results.get(0); // 返回第一个结果
                    }
                });
    }

    @Override
    public <T> List<T> selectList(String statementId, Object parameter) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatement(statementId);
        return executor.query(mappedStatement, parameter);
    }
}
